package cn.niu.controller;

import ch.qos.logback.core.encoder.ByteArrayUtil;
import cn.niu.Live;
import cn.niu.dao.UserInfoMapper;
import cn.niu.model.UserInfo;
import com.github.binarywang.java.emoji.EmojiConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by niusibao on 2017/5/22 0022.
 */
@RestController
@RequestMapping("/demo")
public class DemoController {

    @Autowired
    UserInfoMapper userInfoMapper;

    EmojiConverter emojiConverter = EmojiConverter.getInstance();

    @RequestMapping("/message")
    public Object message() {
        UserInfo userInfo = new UserInfo();
        userInfo.setId("1");
        String str = "  An 😃😀awesome 😃😃string with a few 😃😉emojis!";
        str = emojiConverter.toHtml(str);
        userInfo.setDisplayName(str);
        userInfoMapper.insertSelective(userInfo);
        return "";
    }

    String str = "#EXTM3U\n" +
            "#EXT-X-ALLOW-CACHE:NO\n" +
            "#EXT-X-VERSION:3\n" +
            "#EXT-X-TARGETDURATION:1\n" +
            "#EXT-X-MEDIA-SEQUENCE:%d\n" +
            "#EXTINF:1,\n" +
            "http://192.168.1.183/iis/ts1/%03d.mp3\n" +
            "#EXTINF:1,\n" +
            "http://192.168.1.183/iis/ts1/%03d.mp3\n";

    int ts1 = 1, ts2 = 2, ts3 = 3;

    long lastTime;

    ArrayList<Integer> list;

    @ResponseBody
    @RequestMapping("/myLive.m3u8")
    public void myLive(HttpServletResponse response) throws Exception {
        int length = 70;
        if (list == null) {
            lastTime = System.currentTimeMillis();
            list = new ArrayList<>();
            for (int i = 0; i < 35; i++) {
                list.add((int) (Math.random() * 34) + 1);
            }
        }

        long now = System.currentTimeMillis();

        int sequence = (int) ((now - lastTime) / 1000);

        ts1 = sequence % length + 1;
        ts2 = (sequence + 1) % length + 1;
        ts3 = ((sequence + 2) % length + 1);

        OutputStream out = response.getOutputStream();

        response.addHeader("Content-Type", "application/x-mpegURL");//为response添加响应头
        String result = String.format(str, sequence, ts1, ts2, ts3);

        response.setStatus(200);
        out.write(result.getBytes());
        out.flush();


        System.out.println(String.format("sequence:%d;ts1:%d;ts2:%d;ts3:%d", sequence, ts1, ts2, ts3));
    }

    String m3u8Text = "#EXTM3U\n" +
            "#EXT-X-VERSION:3\n" +
            "#EXT-X-ALLOW-CACHE:NO\n" +
            "#EXT-X-TARGETDURATION:7\n" +
            "#EXT-X-MEDIA-SEQUENCE:%d\n" +
            "#EXTINF:6\n" +
            "audio/%03d.aac\n" +
            "#EXTINF:6\n" +
            "audio/%03d.aac\n" +
            "#EXTINF:6\n" +
            "audio/%03d.aac\n";

//    String m3u8Text = "#EXTM3U\n" +
//            "#EXT-X-VERSION:3\n" +
//            "#EXT-X-ALLOW-CACHE:NO\n" +
//            "#EXT-X-TARGETDURATION:1\n" +
//            "#EXT-X-MEDIA-SEQUENCE:%d\n" +
//            "#EXTINF:0.25\n" +
//            "audio/%03d.mp3\n" +
//            "#EXTINF:0.25\n" +
//            "audio/%03d.mp3\n" +
//            "#EXTINF:0.25\n" +
//            "audio/%03d.mp3\n" +
//            "#EXTINF:0.25\n" +
//            "audio/%03d.mp3\n" +
//            "#EXTINF:0.25\n" +
//            "audio/%03d.mp3\n" +
//            "#EXTINF:0.25\n" +
//            "audio/%03d.mp3\n";

    private static long startTime = System.currentTimeMillis();
    private static int sequence = 0;

    @RequestMapping("/live.m3u8")
    public void live(HttpServletResponse response) throws IOException {

        int length = 35;
        sequence = (int) ((System.currentTimeMillis() - startTime) / 6000);
//sequence++;
        String res = String.format(m3u8Text, sequence, (sequence) % length + 1, (sequence + 1) % length + 1,
                (sequence + 2) % length + 1, (sequence + 3) % length + 1,
                (sequence + 4) % length + 1, (sequence + 5) % length + 1);
        OutputStream out = response.getOutputStream();
        response.addHeader("Content-Type", "application/x-mpegURL");//为response添加响应头
        response.setStatus(200);
        out.write(res.getBytes());
        out.flush();
//        System.out.println(res);
        System.out.println(String.format("sequence:%d;first:%d;second:%d;third:%d;", sequence, (sequence) % length + 1, (sequence + 1) % length + 1, (sequence + 2) % length + 1));
    }

    @RequestMapping("/audio/{id}.aac")
    public void audio(HttpServletResponse response, @PathVariable Integer id) throws IOException {
        System.out.println(id + ".aac");
        RandomAccessFile file = new RandomAccessFile("D:/game/六哲-错错错.aac", "r");

        file.seek((id - 1) * 97143);

        byte[] bytes = new byte[97143];
        file.read(bytes);

        file.close();
        OutputStream out = response.getOutputStream();
        response.addHeader("Content-Type", "audio/mp3");//为response添加响应头
        response.setStatus(200);
        out.write(bytes);
        out.flush();
    }


    private static Map<String, Live> liveMap = new HashMap<>();


    public static Live getLive(String name) {

        Live live = liveMap.get(name);
        if (live == null) {
            synchronized (DemoController.class) {
                live = liveMap.get(name);
                if (live == null) {
                    live = new Live(name);
                    liveMap.put(name, live);
                }
            }
        }
        return live;
    }

    String m3u8TextAll = "#EXTM3U\n" +
            "#EXT-X-VERSION:3\n" +
            "#EXT-X-ALLOW-CACHE:NO\n" +
            "#EXT-X-TARGETDURATION:1\n" +
            "#EXT-X-MEDIA-SEQUENCE:%d\n" +
            "#EXTINF:0.512\n" +
            "%03d.ts\n" +
            "#EXTINF:0.512\n" +
            "%03d.ts\n" +
            "#EXTINF:0.512\n" +
            "%03d.ts\n";

    String m3u8TextAllAAC = "#EXTM3U\n" +
            "#EXT-X-VERSION:3\n" +
            "#EXT-X-ALLOW-CACHE:NO\n" +
            "#EXT-X-TARGETDURATION:1\n" +
            "#EXT-X-MEDIA-SEQUENCE:%d\n" +
            "#EXTINF:0.512\n" +
            "%03d.aac\n" +
            "#EXTINF:0.512\n" +
            "%03d.aac\n" +
            "#EXTINF:0.512\n" +
            "%03d.aac\n";

    @RequestMapping("/{name}/live.m3u8")
    public void liveAll(HttpServletRequest request, HttpServletResponse response, @PathVariable String name) throws IOException {
        String userAgent = request.getHeader("user-agent").toLowerCase();
        String m3u8 = m3u8TextAll;
        if (userAgent.contains("iphone")) {
            m3u8 = m3u8TextAllAAC;
        }

        Live live = getLive(name);

        long seq = live.getSequence();
        String res = String.format(m3u8, seq, seq, seq + 1, seq + 2, seq + 3, seq + 4, seq + 5,
                seq + 6, seq + 7, seq + 8, seq + 9, seq + 10, seq + 11);
        OutputStream out = response.getOutputStream();
        response.addHeader("Content-Type", "application/x-mpegURL");//为response添加响应头
        response.setStatus(200);
        out.write(res.getBytes());
        out.flush();
    }

    /**
     * @param name
     */
    @RequestMapping("/putData")
    public Object putData(String name, String data) throws IOException {
        Live live = getLive(name);
        live.putStream(ByteArrayUtil.hexStringToByteArray(data));
        return 1;
    }

    @RequestMapping("/{name}/info")
    public Object player(HttpServletResponse response, @PathVariable String name) throws IOException {
        Live live = getLive(name);
        return live.getSequence();
    }

    @RequestMapping("/{name}/{id}.ts")
    public void audio(HttpServletResponse response,
                      @PathVariable String name, @PathVariable Integer id) throws IOException {
        System.out.println(id + ".ts");
        Live live = getLive(name);
        OutputStream out = response.getOutputStream();
        byte[] bytes = live.getBytes(id, false);

        response.addHeader("Content-Length", bytes.length + "");
        response.addHeader("Content-Type", "audio/MP2T");//为response添加响应头
        response.setStatus(200);

        out.write(bytes);
        out.flush();
    }

    @RequestMapping("/{name}/{id}.aac")
    public void audioAAc(HttpServletResponse response,
                         @PathVariable String name, @PathVariable Integer id) throws IOException {
        System.out.println(id + ".aac");
        Live live = getLive(name);
        OutputStream out = response.getOutputStream();
        byte[] bytes = live.getBytes(id, true);

//        response.addHeader("");
        response.addHeader("Content-Length", bytes.length + "");
        response.addHeader("Content-Type", "audio/mp3");//为response添加响应头
        response.setStatus(200);

        out.write(bytes);
        out.flush();
    }
}
